﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Text;

namespace ZYing.QPanel
{
    public static class Extensions
    {
        public static void SetExecutionHistoryStore(this SchedulerContext context, IExecutionHistoryStore store)
        {
            context.Put(typeof(IExecutionHistoryStore).FullName, store);
        }

        public static bool TryGetExecutionHistoryStore(this SchedulerContext context, out IExecutionHistoryStore store)
        {
            if (context.TryGetValue(typeof(IExecutionHistoryStore).FullName, out var value) && value is IExecutionHistoryStore cast)
            {
                store = cast;
                return true;
            }
            store = null;
            return false;
        }
        public static TimeSpan GetRunTime(this ExecutionHistoryEntry entry)
        {
            var end = DateTimeOffset.UtcNow;
            if (entry.FinishedTimeUtc != null)
            {
                end = entry.FinishedTimeUtc.Value;
            }
            return end - entry.ActualFireTimeUtc;
        }
        public static JobState GetJobState(this ExecutionHistoryEntry entry)
        {

            if (string.IsNullOrWhiteSpace(entry.ExceptionMessage))
            {
                if (entry.FinishedTimeUtc != null)
                {
                    return JobState.Complated;
                }
                else
                {
                    return JobState.Running;
                }
            }
            else
            {
                return JobState.Fail;
            }
        }

        public static string GetClass(this Type type)
        {
            return type.FullName;
        }

        public static string GetFullClass(this Type type)
        {
            var ass = type.Assembly.GetName().Name;
            return $"{type.FullName},{ass}";
        }

        public static void FireStatus(this IJobExecutionContext context, string status)
        {
            if (context == null) return;
            JobHelper.FireStatus(context, status);
        }
        public static TriggerType GetTriggerType(this ITrigger trigger)
        {
            if (trigger is ICronTrigger)
                return TriggerType.Cron;
            if (trigger is IDailyTimeIntervalTrigger)
                return TriggerType.Daily;
            if (trigger is ISimpleTrigger)
                return TriggerType.Simple;
            if (trigger is ICalendarIntervalTrigger)
                return TriggerType.Calendar;

            return TriggerType.Unknown;
        }
    }
}
